package filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import beans.Member;
import service.MemberService;
import serviceimpl.MemberServiceIpmt;

/**
 * Servlet Filter implementation class AutoLoginFilter
 */
@WebFilter("/AutoLoginFilter")
public class AutoLoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AutoLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		// jpg css js png html login jsp
		// 通过请求路径，将以上选项排除，无关紧要
		String uri = req.getRequestURI();
		// 登录之前先判断有没有登录过
		if (req.getSession().getAttribute("user") == null) {
			// 1.接收请求，获得参数 - Cookie
			Cookie[] cookies = req.getCookies();
			// 2.从cookie中找到用户名和密码
			String username = null;
			String password = null;

			for (int i = 0; cookies != null && i < cookies.length; i++) {
				if (cookies[i].getName().equals("username")) {
					username = cookies[i].getValue();
				}
				if (cookies[i].getName().equals("password")) {
					password = cookies[i].getValue();
				}
			}

			// 3.登录操作 - 参考LoginServlet
			if (username != null && password != null) {
				MemberService ms = new MemberServiceIpmt();
				try {
					Member member = ms.login(username, password);
					req.getSession().setAttribute("member", member);
				} catch (Exception e) {

				}
			}
			// 4.无论是否登录成功，都要放行
			chain.doFilter(request, response);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
